<template>
  <div>
    <el-tree
      ref="tree"
      :data="list"
      :props="{label: 'name'}"
      show-checkbox
      check-strictly
      default-expand-all
      node-key="id"
    />
    <div>
      <el-button @click="hCancel">取消</el-button>
      <el-button type="primary" @click="hSubmit">确定</el-button>
    </div>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permisson'
import { arrayToTree } from '@/utils/index'
import { getRoleDetail, assignPerm } from '@/api/setting'
export default {
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    // 获取所有的权限点
    this.loadPermission()
    // 根据当前的角色id，获取这个角色所具有的权限点信息
    this.loadPermissionById()
  },
  methods: {
    async hSubmit() {
      const permIds = this.$refs.tree.getCheckedKeys()
      const res = await assignPerm({ id: this.roleId, permIds: permIds })
      console.log(res)
      this.$message.success('保存成功')
      this.hCancel()
    },
    hCancel() {
    // 通过父组件去关闭弹层
      this.$emit('close')
    },
    async loadPermission() {
      const res = await getPermissionList()
      this.list = arrayToTree(res.data)
      // console.log(res)
    },
    async loadPermissionById() {
      const res = await getRoleDetail(this.roleId)
      // console.log('获取角色现有的权限', res.data.permIds)
      // console.log(res)
      // 回填
      this.$refs.tree.setCheckedKeys(res.data.permIds)
    }
  }

}
</script>

<style>

</style>
